package com.fyakm.daodejing.test001core;



import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Nature {
    private List<Species> speciesList;

    public Nature() {
        this.speciesList = new ArrayList<>();
    }

    // 初始化物种的方法，在模拟开始时可以添加一些初始物种进来
    public void initializeSpecies(Species initialSpecies) {
        speciesList.add(initialSpecies);
    }

    // 推进大自然的发展，模拟一个时间阶段或者一轮进化过程，这里可以调用进化控制类的方法来让物种进化
    public void evolve(EvolutionController evolutionController, List<String> environmentInputData) throws IOException {
        List<Species> newGeneration = new ArrayList<>();
        for (int i = 0; i < speciesList.size(); i += 2) {
            Species parent1 = speciesList.get(i);
            Species parent2 = speciesList.get(i + 1);
            // 执行Java代码获取实际输出
            List<String> actualOutputList1 = parent1.executeJavaCode();
            List<String> actualOutputList2 = parent2.executeJavaCode();
            // 计算适应度
            double fitness1 = parent1.calculateFitness(actualOutputList1);
            double fitness2 = parent2.calculateFitness(actualOutputList2);
            if (Math.random() < fitness1 && Math.random() < fitness2) { // 根据适应度概率决定是否存活并繁殖
                Species offspring = evolutionController.performGeneticInheritance(parent1, parent2);
                evolutionController.performMutation(offspring);
                newGeneration.add(offspring);
            }
        }
        speciesList = newGeneration;
    }

    // 获取当前所有物种的方法，方便查看模拟情况等
    public List<Species> getSpeciesList() {
        return speciesList;
    }
}